package com.lftea.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.lftea.dao.IEmployeeDAO;
import com.lftea.po.Employee;
import com.lftea.util.StringUtils;

@Repository("employeeDAOImpl")
public class EmployeeDAOImpl implements IEmployeeDAO {
	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	public Employee findById(long employeeId) {
		String sql = "select * from Employee where Employee_ID=?";
		return (Employee) jdbcTemplate.query(sql, new Object[] { employeeId },
				new EmployeeMapper());
	}

	private final class EmployeeMapper implements RowMapper<Employee> {

		public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
			Employee employee = new Employee();
			employee.setId(rs.getLong("Employee_ID"));
			employee.setName(rs.getString("Name"));
			employee.setPassword(rs.getString("password"));
			employee.setRole(rs.getString("Role"));
			return employee;
		}
	}

	@Override
	public List<Employee> findAll() {
		String sql = "select * from Employee";
		return jdbcTemplate.query(sql, new EmployeeMapper());
	}

	@Override
	public void remove(Employee employee) {
		long employeeId = employee.getId();
		String sql = "delete Employee where Employee_ID=?";
		jdbcTemplate.update(sql, new Object[] { employeeId });
	}

	@Override
	public void save(Employee employee) {
		long employeeId = employee.getId();
		String name = StringUtils.toISO(employee.getName());
		String password = employee.getPassword();
		String role = employee.getRole();

		String sql = "select count(*) from Employee where Employee_ID=?";
		int result = jdbcTemplate.queryForInt(sql, new Object[] { employeeId });
		Object[] params = null;
		if (result > 0) {
			sql = "update Employee set name=?,Password=?,role=? where Employee_ID=?";
			params = new Object[] { name, password, role, employeeId };
		} else {
			sql = "insert into Employee(name,Password,Role) values(?,?,?)";
			params = new Object[] { name, password, role };
		}
		jdbcTemplate.update(sql, params);
	}

}
